import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import MapView from '@arcgis/core/views/MapView'
import Map from '@arcgis/core/Map'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Query from '@arcgis/core/rest/support/Query'

// 导出选中的要素，供其他模块使用
export let selectedFeature: Graphic | null = null

// 地块属性表单
export const landParcelForm = reactive({
  FID: null as number | null,
  LandID: '',
  landType: '',
  Area: 0,
  landUse: '',
  ownershipType: '',
  rightHolder: '',
  expirationDate: '',
  acquisitionDate: '',
  updateDate: '',
  parcelStatus: '',
  parcelGrade: '',
  remarks: '',
})

// 地块查询状态
export const queryState = reactive({
  showAttributePanel: false,
  isQuerying: false,
})

// 重置表单
export const resetForm = () => {
  landParcelForm.FID = null
  landParcelForm.LandID = ''
  landParcelForm.landType = ''
  landParcelForm.Area = 0
  landParcelForm.landUse = ''
  landParcelForm.ownershipType = ''
  landParcelForm.rightHolder = ''
  landParcelForm.expirationDate = ''
  landParcelForm.acquisitionDate = ''
  landParcelForm.updateDate = ''
  landParcelForm.parcelStatus = ''
  landParcelForm.parcelGrade = ''
  landParcelForm.remarks = ''
}

// 地块类型选项
export const landTypeOptions = [
  { label: '耕地', value: '耕地' },
  { label: '林地', value: '林地' },
  { label: '草地', value: '草地' },
  { label: '住宅用地', value: '住宅用地' },
  { label: '商业用地', value: '商业用地' },
  { label: '工业用地', value: '工业用地' },
  { label: '交通用地', value: '交通用地' },
  { label: '水域', value: '水域' },
  { label: '其他', value: '其他' },
]

// 地图浏览查询功能
export function useMapBrowseQuery(mapView: MapView | null, map: Map | null) {
  let landParcelLayer: FeatureLayer | null = null

  // 初始化地图查询功能
  const initMapQuery = (mapInstance?: { map: Map; mapView: MapView } | null) => {
    // 如果传入了地图实例，则使用传入的地图实例
    if (mapInstance) {
      map = mapInstance.map
      mapView = mapInstance.mapView
    }

    if (!mapView || !map) return

    // 获取地块图层
    landParcelLayer = map.findLayerById('landParcelLayer') as FeatureLayer
    if (!landParcelLayer) {
      console.error('找不到地块图层')
      return
    }

    // 监听点击事件，用于查询地块信息
    mapView.on('click', async (event) => {
      // 如果正在查询，不执行新的查询
      if (queryState.isQuerying) return

      queryState.isQuerying = true

      try {
        // 转换空间参考
        const mapPoint = event.mapPoint
        // 创建查询对象
        const query = new Query()
        query.geometry = mapPoint
        query.distance = 10 // 增加点击容差
        query.units = 'meters'
        query.spatialRelationship = 'intersects'
        query.returnGeometry = true
        query.outFields = ['*']

        // 查询地块图层
        if (landParcelLayer && landParcelLayer.visible) {
          // 强制刷新图层
          landParcelLayer.refresh()
          const result = await landParcelLayer.queryFeatures(query)

          if (result.features.length > 0) {
            const feature = result.features[0]
            selectedFeature = feature

            // 填充表单数据
            const attributes = feature.attributes
            landParcelForm.FID = attributes.FID
            landParcelForm.LandID = attributes.LandID || ''
            landParcelForm.landType = attributes.landType || ''
            landParcelForm.Area = attributes.Shape__Area || 0
            landParcelForm.landUse = attributes.landUse || ''
            landParcelForm.ownershipType = attributes.ownershipType || ''
            landParcelForm.rightHolder = attributes.rightHolder || ''
            landParcelForm.expirationDate = attributes.expirationDate || ''
            landParcelForm.acquisitionDate = attributes.acquisitionDate || ''
            landParcelForm.updateDate = attributes.updateDate || ''
            landParcelForm.parcelStatus = attributes.parcelStatus || ''
            landParcelForm.parcelGrade = attributes.parcelGrade || ''
            landParcelForm.remarks = attributes.remarks || ''

            // 显示属性面板
            queryState.showAttributePanel = true
          } else {
            // 如果没有选中要素，隐藏属性面板
            selectedFeature = null
            queryState.showAttributePanel = false
            resetForm()
          }
        }
      } catch (error) {
        console.error('查询地块失败:', error)
        ElMessage.error('查询地块失败')
      } finally {
        queryState.isQuerying = false
      }
    })
  }

  // 关闭属性面板
  const closeAttributePanel = () => {
    queryState.showAttributePanel = false
    selectedFeature = null
    resetForm()
  }

  return {
    initMapQuery,
    closeAttributePanel,
    landParcelForm,
    queryState,
    landTypeOptions,
  }
}
